package com.xiliubit.cloudpicture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiliubit.cloudpicture.annotation.AuthCheck;
import com.xiliubit.cloudpicture.common.BaseResponse;
import com.xiliubit.cloudpicture.common.DeleteRequest;
import com.xiliubit.cloudpicture.common.ResultUtils;
import com.xiliubit.cloudpicture.constant.UserConstant;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import com.xiliubit.cloudpicture.model.dto.user.*;
import com.xiliubit.cloudpicture.model.entity.User;
import com.xiliubit.cloudpicture.model.vo.UserInfoVO;
import com.xiliubit.cloudpicture.model.vo.UserLoginVO;
import com.xiliubit.cloudpicture.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user")
@Tag(name = "用户接口")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        log.info("用户注册: {}", userRegisterRequest);
        // 1. 校验参数
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        long userId = userService.userRegister(userRegisterRequest);

        // 2.返回用户id
        return ResultUtils.success(userId);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录参数
     * @param request          request
     * @return 脱敏的登录用户信息
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public BaseResponse<UserLoginVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        log.info("用户登录：{}", userLoginRequest);
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        UserLoginVO userLoginVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(userLoginVO);
    }

    /**
     * 获取当前登录用户
     *
     * @param request 请求
     * @return 当前登录用户信息
     */
//    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    @GetMapping("/get/login")
    @Operation(summary = "获取当前登录用户")
    public BaseResponse<UserInfoVO> getLoginUser(HttpServletRequest request) {
        log.info("获取当前登录用户：{}", request);
        User user = userService.getLoginUser(request);
        // 用户信息脱敏
        UserInfoVO userInfo = userService.getUserInfo(user);
        return ResultUtils.success(userInfo);
    }

    /**
     * 用户注销
     *
     * @param request 请求
     * @return 退出登录是否成功
     */
    @PostMapping("/logout")
    @Operation(summary = "用户注销")
//    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        log.info("用户注销");
        return ResultUtils.success(userService.userLogout(request));
    }

    /**
     *  分页获取用户封装列表（管理员）
     * @param userQueryRequest 用户查询参数
     * @return 用户封装列表
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @Operation(summary = "分页获取用户封装列表（管理员）")
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserInfoVO>> listUserInfoByPage(@RequestBody UserQueryRequest userQueryRequest){
        log.info("分页获取用户封装列表（管理员）：{}", userQueryRequest);
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = userQueryRequest.getCurrent();
        int pageSize = userQueryRequest.getPageSize();
        Page<User> page = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserInfoVO> userInfoVOPage = new Page<>(current, pageSize, page.getTotal());
        List<UserInfoVO> userVOList = userService.getUserVOList(page.getRecords());
        userInfoVOPage.setRecords(userVOList);
        return ResultUtils.success(userInfoVOPage);
    }

    /**
     * 获取用户信息（仅管理员）
     *
     * @param id 用户id
     * @return 用户信息
     */
    @GetMapping("/get")
    @Operation(summary = "根据id获取用户（管理员）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(Long id) {
        log.info("获取用户信息：{}", id);
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取用户VO
     * @param id  id
     * @return 脱敏后的用户信息
     */
    @GetMapping("/get/vo")
    @Operation(summary = "根据id获取用户VO")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<UserInfoVO> getUserVOById(Long id) {
        log.info("根据 id 获取用户VO:{}", id);
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        UserInfoVO userInfoVO = userService.getUserInfo(user);
        return ResultUtils.success(userInfoVO);
    }

    /**
     *  用户添加(管理员)
     * @param userAddRequest 用户添加请求参数
     * @return 用户ID
     */
    @PostMapping("/add")
    @Operation(summary = "用户添加(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> userAdd(UserAddRequest userAddRequest){
        log.info("用户添加请求参数：{}", userAddRequest);
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        Long id = userService.userAdd(userAddRequest);
        ThrowUtils.throwIf(id == null, ErrorCode.SYSTEM_ERROR);
        return ResultUtils.success(id);
    }

    /**
     * 用户更新(管理员)
     * @param userUpdateRequest 修改用户信息
     * @return 修改结果
     */
    @PutMapping("/update")
    @Operation(summary = "用户更新(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> userUpdate(@RequestBody UserUpdateRequest userUpdateRequest){
        log.info("用户更新:{}", userUpdateRequest);
        ThrowUtils.throwIf(userUpdateRequest == null || userUpdateRequest.getId() == null,
                ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        return ResultUtils.success(result);
    }

    /**
     * 用户编辑
     *
     * @param userEditRequest 用户编辑请求参数
     * @return 编辑结果
     */
    @PostMapping("/edit")
    @Operation(summary = "用户编辑（管理员）")
    public BaseResponse<Boolean> userEdit(@RequestBody UserEditRequest userEditRequest, HttpServletRequest request) {
        log.info("用户编辑:{}", userEditRequest);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        boolean result = userService.userEdit(userEditRequest, loginUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "修改失败");
        return ResultUtils.success(true);
    }

    /**
     * 删除用户（管理员）
     *
     * @param deleteRequest 删除请求参数
     * @return 删除结果
     */
    @PostMapping("/delete")
    @Operation(summary = "删除用户(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        log.info("删除用户:{}", deleteRequest);
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() == null,
                ErrorCode.PARAMS_ERROR);
        boolean result = userService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(result);
    }
}
